package org.adream.account.rest.frontApi;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.adream.account.entity.CmsLogEntity;
import org.adream.account.entity.TagEntity;
import org.adream.account.entity.UserDetailEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.rest.api.model.PhotoForm;
import org.adream.account.rest.api.model.UserDetailInfoForm;
import org.adream.account.service.ADreamServiceException;
import org.adream.account.service.CmsLogService;
import org.adream.account.service.UserDetailService;
import org.adream.account.service.UserService;
import org.adream.account.util.Constant;
import org.adream.account.util.UserUtil;
import org.adream.account.util.Utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

/**
 * user 详细资料 
 * @author sl
 *
 */
@RequestMapping(value = "/userDetailFront")
@Controller
public class UserDetailFrontApiController {
	
	private final static Logger logger = LoggerFactory.getLogger(UserDetailFrontApiController.class);
	
	@Autowired
	private UserDetailService userDetailService;
	
	@Autowired
	private UserService userService;
	
	@Value("${image.file.path.userpic}")
    private String userPicPath;  //用户图片
	
	@Autowired
	private CmsLogService cmsLogService;
	
	/**
	 * 新增
	 * @param userDetail
	 * @return
	 */
	@RequestMapping(value = "", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> addUserDetail(@RequestBody UserDetailEntity userDetail) {
		if(userDetail == null) {				
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		return userDetailService.addUserDetail(userDetail);
	}

	/**
	 * 根据uid更新
	 * @param uid user id
	 * @param userDetail
	 * @return
	 */
	@RequestMapping(value = "/save", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
	@ResponseBody
	public ResultModel<?> updateUserDetail(@RequestBody UserDetailEntity userDetail,
			HttpServletRequest request) {
		try {
			String uid = UserUtil.getUidByRequest(request);
			if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(userDetail)) {				
				return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
			}
			
			//数据长度校验
			if(userDetail.getAccountName() != null && userDetail.getAccountName().length() > Constant.LONG_DATA_LENGTH) {
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "账户名称输入过长,请精简", null);
			}
			
			if(userDetail.getBankAccount() != null && userDetail.getBankAccount().length() > Constant.COMMON_DATA_LENGTH) {
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "银行账号输入过长,请精简", null);
			}
			
			if(userDetail.getDepositBank() != null && userDetail.getDepositBank().length() > Constant.COMMON_DATA_LENGTH) {
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "开户行输入过长,请精简", null);
			}
			
			if(userDetail.getAopenBranch() != null && userDetail.getAopenBranch().length() > Constant.LONG_DATA_LENGTH) {
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "开户支行输入过长,请精简", null);
			}
			
			userDetailService.updateUserDetail(uid,userDetail);
			return new ResultModel<String>(ResultModel.SUCCESS, "成功更新userDetail", null);
		} catch (ADreamServiceException e) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, e.getMessage(), null);
		}
	}
	
	/**
	 * 更新详细资料
	 * @param form 详细资料表单
	 * @return
	 */
	@RequestMapping(value = "/updateDetailInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateDetailInfo(@RequestBody UserDetailInfoForm form,
			HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(form)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
		}
		if(StringUtils.isEmpty(uid)){
			return new ResultModel<String>(ResultModel.ERR_USER_INFO, ResultModel.ERR_USER_INFO_MSG, null);
		}
		
		//数据长度校验
		if(form.getAddress() != null && form.getAddress().length() > Constant.LONG_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "详细地址输入过长,请精简", null);
		}
		
		if(form.getReceiver() != null && form.getReceiver().length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "收货人输入过长,请精简", null);			
		}
		
		if(form.getPhone() != null && form.getPhone().length() > 20) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "手机号码输入过长,请精简", null);
		}
		
		UserDetailEntity detail = new UserDetailEntity();
		try {
			Utils.copyPropertiesIgnoreNull(form, detail);
			userDetailService.updateUserDetail(uid,detail);
		} catch (ADreamServiceException e) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, e.getMessage(), null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, "成功", "success");
	}
	
	/**
	 * 更新用户头像
	 * @param form	图片表单
	 * @param request
	 * @return
	 * @throws ADreamServiceException
	 */
	@RequestMapping(value = "/updatePhoto", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updatePhoto(@RequestBody PhotoForm form,HttpServletRequest request) throws ADreamServiceException {
	
			String uid = UserUtil.getUidByRequest(request);
			if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(form)) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
			}
			try {
				if(form.getBase64url().startsWith(Constant.PART_BEGIN_BASE64URL)) {
					String content = form.getBase64url().substring(form.getBase64url().indexOf(",") + 1);
					String resp = Utils.instance.verifyFileContent(content);
					
					String imgMd5 = DigestUtils.md5Hex(content);
					CmsLogEntity cmsLogEntity = new CmsLogEntity();
					cmsLogEntity.setUid(uid);
					cmsLogEntity.setAction(CmsLogEntity.IMAGE_ACTION);
					cmsLogEntity.setImgMd5(imgMd5);
					cmsLogEntity.setResponse(resp);
					
					cmsLogService.addEntity(cmsLogEntity);
					
					JSONObject jsonObject = JSONObject.parseObject(resp);
				    Boolean evilFlag = jsonObject.getJSONObject("Response").getJSONObject("Data").getBoolean("EvilFlag");
				    if(evilFlag) {
				    	return new ResultModel<String>(ResultModel.ERR_PARAM, "头像涉嫌违规，请更换后上传！", null);
				    }
				}
			} catch (TencentCloudSDKException e) {
				logger.error("图片安全性检测 error~~！！！");
			}
			
			boolean success = userDetailService.updatePhoto(uid, form.getBase64url(), form.getX(), form.getY(), 
					form.getWidth(), form.getHeight(), form.getPhoto());
			if(success) {
				return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
			} else {
				return new ResultModel<String>(ResultModel.ERR_SERVICE, "头像保存出错", null);
			}
		
	}
	
	/**
	 * 查询用户详细资料
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryDetailInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryDetailInfo(HttpServletRequest request){
		logger.debug("从request中得到uid,根据uid查询基本信息");
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {				
			return new ResultModel<String>(ResultModel.ERR_PARAM, "权限错误,请重新登录", null);
		}
		UserDetailEntity userDetail = userDetailService.queryUserDetailByUid(uid);
		if(userDetail == null){
			return new ResultModel<UserDetailEntity>(ResultModel.NOT_FOUND_OBJECT,"用户详细信息未维护", null);
		}
		
		if(request.getParameter("tagFlag")!=null && "true".equals(request.getParameter("tagFlag"))){
			//logger.debug("从request中得到uid,根据uid查询基本信息");
			List<TagEntity> tags = userService.queryTagByUid(uid);
			if(!StringUtils.isEmpty(userDetail) && !Utils.isEmptyCollection(tags)) {
				userDetail.setTags(tags);
			}
		}
		
		//敏感信息带*号返回
		//收货地址  手机号
		if(!StringUtils.isEmpty(userDetail.getPhone())) {
			userDetail.setPhone(Utils.replaceXing(userDetail.getPhone(), 3, 4));
		}
		
		//银行信息 银行账号
		if(!StringUtils.isEmpty(userDetail.getBankAccount())) {
			userDetail.setBankAccount(Utils.replaceXing(userDetail.getBankAccount(), 4, 4));
		}
		return new ResultModel<UserDetailEntity>(ResultModel.SUCCESS, "查询成功", userDetail);
	}
	
	
	/**
	 * 查询详细资料
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryDetail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryDetail(HttpServletRequest request){
		logger.info("查询当前user的详细资料");
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败,请求参数为空", null);
		}
		UserDetailEntity userDetail;
		userDetail = userDetailService.queryUserDetailByUid(uid);
		if(userDetail == null) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的数据", null);
		}
		return new ResultModel<UserDetailEntity>(ResultModel.SUCCESS, "查询成功", userDetail);
	}
}